#ifndef __LISTEN_H__
#define __LISTEN_H__
#include <iostream>
#include "channel.hpp"
#include "Socket.hpp"
#include "InetAddr.hpp"

using namespace SocketModule;

class Listen : public Connection
{
public:
    Listen(int port = -1) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildTcpSocketMethod(_port);
        SetNonBlock(_listensock->Fd());
        SetEvent(EPOLLIN | EPOLLET);
    }
    void Recv() override
    {
        // accept
        InetAddr client;
        // ET 模式
        while (true)
        {
            int sockfd = _listensock->Accept(&client);
            if (sockfd == ACCEPT_DONE)
            {
                break; // 底层没有连接了
            }
            else if (sockfd == ACCEPT_ERR)
            {
                break; // 读取出错了
            }
            else if (sockfd == ACCEPT_CONTINUE)
            {
                continue; // 被信号打断，继续读取
            }
            else
            {
                std::shared_ptr<Connection> conn = std::make_shared<Channel>(sockfd, client);
                conn->SetEvent(EPOLLIN | EPOLLET);
                if (_handler != nullptr)
                    conn->RegisterHanlder(_handler);

                GetOwner()->AddConnection(conn);
            }
        }
    }
    void Send() override
    {
    }
    void Excpeter() override
    {
    }
    int getFd()
    {
        return _listensock->Fd();
    }
    ~Listen() {}

private:
    int _port;
    std::unique_ptr<Socket> _listensock;
};
#endif